package com.easpeed.user

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.RadioGroup
import android.widget.TextView
import androidx.core.util.Consumer
import androidx.databinding.DataBindingUtil
import com.bigyu.utils.Logger
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ToastUtils
import com.easpeed.common.CommonConsts
import com.easpeed.comon.bean.AppOperateBean
import com.easpeed.comon.bean.Authentication
import com.easpeed.comon.bean.BaseData
import com.easpeed.comon.bean.ChannelSettingBean
import com.easpeed.comon.bean.DataBattery
import com.easpeed.comon.bean.Version
import com.easpeed.comon.bean.home
import com.easpeed.comon.bean.otdrTtest
import com.easpeed.comon.bean.test
import com.easpeed.comon.consts.ConstsApi
import com.easpeed.comon.consts.CustomSetting
import com.easpeed.comon.database.DataBaseUtils
import com.easpeed.comon.database.bean.CommonDataSqlBean
import com.easpeed.comon.dialog.UploadCacheDataDialog
import com.easpeed.comon.memorycache.CommonMemoryCache
import com.easpeed.comon.ui.CommonRouteActivity
import com.easpeed.comon.utils.ApiHelper.checkVersion
import com.easpeed.comon.utils.CacheHelper
import com.easpeed.comon.utils.CommonOperateUtils
import com.easpeed.comon.utils.DownloadHelper
import com.easpeed.comon.utils.LocationHelper
import com.easpeed.comon.utils.SendCommand
import com.easpeed.comon.utils.SendCommand.commandToStr
import com.easpeed.comon.utils.SocketHelper
import com.easpeed.comon.utils.SocketHelper.startSocket
import com.easpeed.comon.utils.bytesToHex
import com.easpeed.comon.utils.setViewsOnclickListener
import com.easpeed.elevator.databinding.ActivityUserMainBinding
import com.easpeed.elevator.ui.OTDROpticTestingActivity
import com.easpeed.elevator.ui.OpticTestingActivity
import com.easpeed.user.dialog.UserDialogHelper
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe


class UserMainActivity : UserBaseActivity() {

    var binding: ActivityUserMainBinding? = null

    lateinit var locationHelper: LocationHelper

    private var channel: String? = "1"
    private var channelName: String? = "通道1"


    @SuppressLint("SetTextI18n")
    override fun initView() {

        EventBus.getDefault().register(this)

        checkVersion(Consumer<BaseData<Version>> { versionBaseData: BaseData<Version> ->
            Logger.e("TAG", "checkVersion:$versionBaseData")
            try {
                if (versionBaseData.data!!.version.toInt() > AppUtils.getAppVersionCode()) {
                    DownloadHelper(this).init("更新应用", versionBaseData.data!!.url)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        })
        DataBaseUtils.saveSingleDataByType("aaa", CommonDataSqlBean().apply {
            this.createTimeMills = System.currentTimeMillis()
            this.updateTimeMills = System.currentTimeMillis()
        })

//        SignalStrengthListener(this).start()
//
//        // position:0～5数值 0:无手机卡或者无信号强度 1～5 手机信号轻度，依次增大
//        PhoneStateUtils.registerPhoneStateListener(this, object : MyPhoneStateListenerListener {
//
//            @RequiresApi(Build.VERSION_CODES.M)
//            override fun onSignalStrengthsChanged(p0: SignalStrength?) {
//                Logger.e("TAG", "获取到onSignalStrengthsChanged: ${p0?.level}")
//
//            }
//        })


        locationHelper = LocationHelper()
        locationHelper.init(this, true)
        locationHelper.testStartLocationService(this)
        binding = DataBindingUtil.setContentView(this, com.easpeed.elevator.R.layout.activity_user_main)

        if (!CustomSetting.use8ChannelData) {
            binding?.chanel5?.visibility = View.GONE
            binding?.chanel6?.visibility = View.GONE
            binding?.chanel7?.visibility = View.GONE
            binding?.chanel8?.visibility = View.GONE
        }

        if (CommonConsts.isPad) {
            binding?.layoutLandscape?.visibility = View.VISIBLE
            binding?.layoutPortrait?.visibility = View.GONE
        } else {
            binding?.layoutLandscape?.visibility = View.GONE
            binding?.layoutPortrait?.visibility = View.VISIBLE
        }

        ImmersionBar.with(this)
            .statusBarDarkFont(false) // 设置状态栏字体为深色
            .transparentStatusBar()  // 透明状态栏
            .fitsSystemWindows(true)
//            .applySystemFits(false)
            .statusBarColor(com.easpeed.elevator.R.color.colorTitleBar)
            .init()

        binding?.loginOut?.setOnClickListener {
            UserDialogHelper.showNoticeDialog(mContext, "退出登录", "确定退出当前账号吗？", {
                CacheHelper.instance().apply {
                    remove("isLogin")
                    remove("loginCache")
                }
                SocketHelper.stopSocket()
                CommonOperateUtils.moveToClearTask(UserLoginActivity::class.java, application)
            })
            //            holder.setActivated(R.id.xunfeng, !holder.getActivated(R.id.xunfeng));
//            ToastUtils.showShort("点击了寻峰");
//            RouteListDialog().show(mContext)

//            RouteUploadDialog().show(mContext, bean)
        }


        binding?.layoutDeviceInfo?.setOnClickListener {
            CommonOperateUtils.moveTo(mContext, UserDeviceInfoActivity::class.java)
        }

        binding?.root.setViewsOnclickListener(com.easpeed.elevator.R.id.layout_first, com.easpeed.elevator.R.id.layout_first_1) {
            if (SocketHelper.isConnected()) {
                var dvsZsl: String? = ""
                var otdrZsl: String? = ""
                val pdjl = sp.getString("pdjl", "70")

                when (channelName) {
                    "通道1" -> {
                        dvsZsl = sp.getString("chanel_1_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_1_otdr", "1.467")
                    }

                    "通道2" -> {
                        dvsZsl = sp.getString("chanel_2_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_2_otdr", "1.467")
                    }

                    "通道3" -> {
                        dvsZsl = sp.getString("chanel_3_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_3_otdr", "1.467")
                    }

                    "通道4" -> {
                        dvsZsl = sp.getString("chanel_4_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_4_otdr", "1.467")
                    }

                    "通道5" -> {
                        dvsZsl = sp.getString("chanel_5_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_5_otdr", "1.467")
                    }

                    "通道6" -> {
                        dvsZsl = sp.getString("chanel_6_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_6_otdr", "1.467")
                    }

                    "通道7" -> {
                        dvsZsl = sp.getString("chanel_7_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_7_otdr", "1.467")
                    }

                    "通道8" -> {
                        dvsZsl = sp.getString("chanel_8_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_8_otdr", "1.467")
                    }
                }

                val bundle = Bundle()
                bundle.putString("channel", channel)
                bundle.putString("channelName", channelName)
                bundle.putString("dvsZsl", dvsZsl)
                bundle.putString("otdrZsl", otdrZsl)
                bundle.putString("pdjl", pdjl)
                bundle.putInt("channelIndex",  CommonMemoryCache.channelCache.channelIndex)

                OpticTestingActivity.start(mContext, bundle)
                SocketHelper.sendCommand(SendCommand.commandAppOperate, AppOperateBean().test())
            } else {
                if (TextUtils.isEmpty(CommonConsts.targetDeviceId)) {
                    UserDialogHelper.showNoticeDialog(mContext, "扫码连接", "是否扫码连接到设备", {
                        CommonOperateUtils.moveTo(mContext, UserScanActivity::class.java)
                    })
                } else {
                    UserDialogHelper.showNoticeDialog(mContext, "连接设备", "是否连接到设备${CommonConsts.targetDeviceId}", {
                        startSocket(ConstsApi.socketHost, ConstsApi.socketPort, CommonConsts.targetDeviceId)
                    })
                }
            }
        }
        binding?.root.setViewsOnclickListener(com.easpeed.elevator.R.id.layout_second, com.easpeed.elevator.R.id.layout_second_2) {
            if (SocketHelper.isConnected()) {
                var dvsZsl: String? = ""
                var otdrZsl: String? = ""
                val pdjl = sp.getString("pdjl", "70")

                when (channelName) {
                    "通道1" -> {
                        dvsZsl = sp.getString("chanel_1_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_1_otdr", "1.467")
                    }

                    "通道2" -> {
                        dvsZsl = sp.getString("chanel_2_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_2_otdr", "1.467")
                    }

                    "通道3" -> {
                        dvsZsl = sp.getString("chanel_3_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_3_otdr", "1.467")
                    }

                    "通道4" -> {
                        dvsZsl = sp.getString("chanel_4_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_4_otdr", "1.467")
                    }

                    "通道5" -> {
                        dvsZsl = sp.getString("chanel_5_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_5_otdr", "1.467")
                    }

                    "通道6" -> {
                        dvsZsl = sp.getString("chanel_6_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_6_otdr", "1.467")
                    }

                    "通道7" -> {
                        dvsZsl = sp.getString("chanel_7_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_7_otdr", "1.467")
                    }

                    "通道8" -> {
                        dvsZsl = sp.getString("chanel_8_dvs", "1.467")
                        otdrZsl = sp.getString("chanel_8_otdr", "1.467")
                    }
                }

                val bundle = Bundle()
                bundle.putString("channel", channel)
                bundle.putString("channelName", channelName)
                bundle.putString("dvsZsl", dvsZsl)
                bundle.putString("otdrZsl", otdrZsl)
                bundle.putString("pdjl", pdjl)
                bundle.putInt("channelIndex",  CommonMemoryCache.channelCache.channelIndex)

                OTDROpticTestingActivity.start(mContext, bundle)
                SocketHelper.sendCommand(SendCommand.commandAppOperate, AppOperateBean().otdrTtest())
            } else {
                if (TextUtils.isEmpty(CommonConsts.targetDeviceId)) {
                    UserDialogHelper.showNoticeDialog(mContext, "扫码连接", "是否扫码连接到设备", {
                        CommonOperateUtils.moveTo(mContext, UserScanActivity::class.java)
                    })
                } else {
                    UserDialogHelper.showNoticeDialog(mContext, "连接设备", "是否连接到设备${CommonConsts.targetDeviceId}", {
                        startSocket(ConstsApi.socketHost, ConstsApi.socketPort, CommonConsts.targetDeviceId)
                    })
                }
            }
//            when (it.id) {
//                com.easpeed.elevator.R.id.layout_second -> {
//                    CommonOperateUtils.moveTo(mContext, UserLineManageActivity::class.java)
//                }
//
//                com.easpeed.elevator.R.id.layout_second_2 -> {
//                    LineManageActivity.start(mContext)
//                }
//            }
        }
        binding?.root.setViewsOnclickListener(com.easpeed.elevator.R.id.layout_fourth, com.easpeed.elevator.R.id.layout_fourth_4) {
            CommonOperateUtils.moveTo(mContext, UserScanActivity::class.java)
        }
        binding?.root.setViewsOnclickListener(com.easpeed.elevator.R.id.layout_third, com.easpeed.elevator.R.id.layout_third_3) {
            if (CommonConsts.targetDeviceId.isEmpty()) {
                ToastUtils.showShort("请先扫码连接设备,再使用此功能")
                return@setViewsOnclickListener
            }
            CommonOperateUtils.moveTo(mContext, CommonRouteActivity::class.java)
        }
//        binding?.root.setViewsOnclickListener(com.easpeed.elevator.R.id.layout_fourth, com.easpeed.elevator.R.id.layout_fourth_4) {
//            CommonOperateUtils.moveTo(mContext, UserScanActivity::class.java)
//        }


        binding?.layoutChanel?.setOnCheckedChangeListener { radioGroup, i ->

            when (i) {
                com.easpeed.elevator.R.id.chanel_1 -> {
                    channel = sp.getString("channel_1", "1.467")
                    CommonMemoryCache.channelCache.channelIndex = 0
                }

                com.easpeed.elevator.R.id.chanel_2 -> {
                    channel = sp.getString("channel_2", "1.467")

                    CommonMemoryCache.channelCache.channelIndex = 1
                }

                com.easpeed.elevator.R.id.chanel_3 -> {
                    channel = sp.getString("channel_3", "1.467")

                    CommonMemoryCache.channelCache.channelIndex = 2
                }

                com.easpeed.elevator.R.id.chanel_4 -> {
                    channel = sp.getString("channel_4", "1.467")
                    CommonMemoryCache.channelCache.channelIndex = 3
                }

                com.easpeed.elevator.R.id.chanel_5 -> {
                    channel = sp.getString("channel_5", "1.467")
                    CommonMemoryCache.channelCache.channelIndex = 4
                }

                com.easpeed.elevator.R.id.chanel_6 -> {
                    channel = sp.getString("channel_6", "1.467")
                    CommonMemoryCache.channelCache.channelIndex = 5
                }

                com.easpeed.elevator.R.id.chanel_7 -> {
                    channel = sp.getString("channel_7", "1.467")
                    CommonMemoryCache.channelCache.channelIndex = 6
                }

                com.easpeed.elevator.R.id.chanel_8 -> {
                    channel = sp.getString("channel_8", "1.467")
                    CommonMemoryCache.channelCache.channelIndex = 7
                }
            }
            //不执行查询
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        sendSerialData(query);
//                    }
//                }, 1000);


            channelName = (findViewById<TextView>(i)).text.toString()

            SocketHelper.sendCommand(SendCommand.changeChannelCommand.bytesToHex(), Gson().toJson(CommonMemoryCache.channelCache))
        }

        SocketHelper.addResultListener(javaClass.simpleName) { tcpData ->
            val commandStr = tcpData.commandStr
            if (tcpData.any is ChannelSettingBean) {
                val channelSettingBean = tcpData.any as ChannelSettingBean
                Logger.e("TAG", channelSettingBean.toString())
                val radioGroup = binding?.layoutChanel as RadioGroup
                if (channelSettingBean.channelIndex != CommonMemoryCache.channelCache.channelIndex) {
                    val view = radioGroup.getChildAt(channelSettingBean.channelIndex)
                    view.performClick()
                    ToastUtils.showShort("切换通道成功")
                }
            }

            //收到电池数据
            if (tcpData.any is DataBattery && (tcpData.any as DataBattery).type == 1) {
                val dataBattery = tcpData.any as DataBattery
                binding?.batteryLevel?.text = "设备电量:${dataBattery.batteryLevel}"

//                binding?.batteryView?.setBatteryLevel(dataBattery.batteryLevel)
            }

            if (commandToStr(SendCommand.commandSyncOTDRSetting) == tcpData.commandStr) {
                try {
                    val data = tcpData.any as HashMap<String, String>
                    editor.putString("chanel_1_otdr", data["chanel_1"])
                    editor.putString("chanel_2_otdr", data["chanel_2"])
                    editor.putString("chanel_3_otdr", data["chanel_3"])
                    editor.putString("chanel_4_otdr", data["chanel_4"])
                    editor.putString("chanel_5_otdr", data["chanel_5"])
                    editor.putString("chanel_6_otdr", data["chanel_6"])
                    editor.putString("chanel_7_otdr", data["chanel_7"])
                    editor.putString("chanel_8_otdr", data["chanel_8"])
                    editor.commit()
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
            }
            if (commandToStr(SendCommand.commandSyncDVSSetting) == tcpData.commandStr) {
                try {
                    val data = tcpData.any as HashMap<String, String>
                    editor.putString("chanel_1_dvs", data["chanel_1"])
                    editor.putString("chanel_2_dvs", data["chanel_2"])
                    editor.putString("chanel_3_dvs", data["chanel_3"])
                    editor.putString("chanel_4_dvs", data["chanel_4"])
                    editor.putString("chanel_5_dvs", data["chanel_5"])
                    editor.putString("chanel_6_dvs", data["chanel_6"])
                    editor.putString("chanel_7_dvs", data["chanel_7"])
                    editor.putString("chanel_8_dvs", data["chanel_8"])
                    editor.putString("pdjl", data["pdjl"])
                    editor.commit()
                } catch (e: java.lang.Exception) {
                }
            }

        }


        binding?.chanel1?.isChecked = true


        if (!CacheHelper.instance().getBooleanValue("isUploadCache") && !CommonConsts.targetDeviceId.isEmpty()) {
            UploadCacheDataDialog().show(mContext)
        }
    }

    override fun onResume() {
        super.onResume()
        locationHelper.start(this, true)
        SocketHelper.sendCommand(SendCommand.commandAppOperate, AppOperateBean().home())
        SocketHelper.sendCommand(SendCommand.commandSyncBattery.bytesToHex(), Gson().toJson(DataBattery(0)))
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)

        locationHelper.stopLocationService()
        locationHelper.release()
        locationHelper.stop()
        Logger.e("TAG", "onDestroy: -------------")
        SocketHelper.stopSocket()
        SocketHelper.removeResultListener(javaClass.simpleName)
        super.onDestroy()
    }


    @Subscribe
    fun onEventMainThread(event: Authentication) {
        val loginCache = CacheHelper.instance().getBooleanValue("loginCache")
        Logger.e("TAG", "onEventMainThread:  登录过期   $loginCache")
        if (loginCache) {
            ToastUtils.showShort("${event.msg}")
            CacheHelper.instance().apply {
                this.remove("loginCache")
                this.remove("isLogin")
            }

            val intent = Intent(this, UserLoginActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
        }
    }


}